<template>
  <div class="task-form-overlay">
    <div class="task-form">
      <h2>{{ isEditing ? '编辑任务' : '新建任务' }}</h2>
      <form @submit.prevent="saveTask">
        <div class="form-group">
          <label for="taskName">任务名称</label>
          <input
            id="taskName"
            v-model="formData.name"
            type="text"
            required
            :class="{ 'error': errors.name }"
          />
          <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
        </div>

        <div class="phases-container">
          <h3>任务阶段</h3>
          <div v-for="(phase, index) in formData.phases" :key="index" class="phase-item">
            <div class="phase-header">
              <input
                v-model="phase.name"
                :placeholder="`阶段 ${index + 1}`"
                class="phase-name-input"
              />
              <button type="button" @click="removePhase(index)" v-if="formData.phases.length > 1">
                删除
              </button>
            </div>
            <div class="phase-dates">
              <div class="form-group">
                <label :for="'startDate' + index">开始日期</label>
                <input
                  :id="'startDate' + index"
                  v-model="phase.startDate"
                  type="date"
                  required
                  :class="{ 'error': errors[`phase${index}Start`] }"
                />
                <span v-if="errors[`phase${index}Start`]" class="error-message">
                  {{ errors[`phase${index}Start`] }}
                </span>
              </div>
              <div class="form-group">
                <label :for="'endDate' + index">结束日期</label>
                <input
                  :id="'endDate' + index"
                  v-model="phase.endDate"
                  type="date"
                  required
                  :class="{ 'error': errors[`phase${index}End`] }"
                />
                <span v-if="errors[`phase${index}End`]" class="error-message">
                  {{ errors[`phase${index}End`] }}
                </span>
              </div>
            </div>
          </div>
          <button
            type="button"
            @click="addPhase"
            class="add-phase-btn"
            v-if="formData.phases.length < 5"
          >
            添加阶段
          </button>
        </div>

        <div class="form-actions">
          <button type="button" @click="$emit('cancel')">取消</button>
          <button type="submit">保存</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted } from 'vue';
import type { Task, TaskPhase } from '../types/task';
import { validateTaskName, validatePhaseDate } from '../utils/validators';

const props = defineProps<{
  task: Task | null;
}>();

const emit = defineEmits<{
  (e: 'save', task: Task): void;
  (e: 'cancel'): void;
}>();

const isEditing = computed(() => !!props.task);

const formData = reactive<{
  name: string;
  phases: TaskPhase[];
}>({
  name: '',
  phases: [
    {
      name: '阶段1',
      startDate: '',
      endDate: ''
    }
  ]
});

const errors = reactive<Record<string, string>>({});

onMounted(() => {
  if (props.task) {
    formData.name = props.task.name;
    formData.phases = props.task.phases.map(phase => ({
      name: phase.name,
      startDate: phase.startDate.split('T')[0],
      endDate: phase.endDate.split('T')[0],
    }));
  } else {
    // 设置默认日期为今天和一个月后
    const today = new Date();
    const nextMonth = new Date();
    nextMonth.setMonth(nextMonth.getMonth() + 1);
    
    formData.phases = [
      {
        name: '阶段1',
        startDate: today.toISOString().split('T')[0],
        endDate: nextMonth.toISOString().split('T')[0],
      },
    ];
  }
});

const addPhase = () => {
  if (formData.phases.length < 5) {
    const lastPhase = formData.phases[formData.phases.length - 1];
    const lastEndDate = new Date(lastPhase.endDate);
    const newStartDate = new Date(lastEndDate);
    const newEndDate = new Date(lastEndDate);
    newEndDate.setMonth(newEndDate.getMonth() + 1);
    
    formData.phases.push({
      name: `阶段${formData.phases.length + 1}`,
      startDate: newStartDate.toISOString().split('T')[0],
      endDate: newEndDate.toISOString().split('T')[0],
    });
  }
};

const removePhase = (index: number) => {
  if (formData.phases.length > 1) {
    formData.phases.splice(index, 1);
  }
};

const validateForm = (): boolean => {
  errors.name = validateTaskName(formData.name);
  
  formData.phases.forEach((phase, index) => {
    errors[`phase${index}Start`] = '';
    errors[`phase${index}End`] = '';
    
    const dateError = validatePhaseDate(phase.startDate, phase.endDate);
    if (dateError) {
      errors[`phase${index}End`] = dateError;
    }
  });
  
  // 检查是否有错误
  return !Object.values(errors).some(error => error);
};

const saveTask = () => {
  if (!validateForm()) {
    return;
  }
  
  const task: Task = {
    id: props.task?.id || '',
    name: formData.name,
    phases: formData.phases.map(phase => ({
      name: phase.name,
      startDate: new Date(phase.startDate).toISOString(),
      endDate: new Date(phase.endDate).toISOString(),
    })),
    createTime: props.task?.createTime || new Date().toISOString(),
    updateTime: new Date().toISOString(),
  };
  
  emit('save', task);
};
</script>

<style scoped lang="less">
.task-form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.task-form {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

  h2 {
    margin-top: 0;
    margin-bottom: 20px;
  }

  .form-group {
    margin-bottom: 16px;

    label {
      display: block;
      margin-bottom: 4px;
      font-weight: bold;
    }

    input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
      
      &.error {
        border-color: #f44336;
      }
    }

    .error-message {
      color: #f44336;
      font-size: 0.8em;
      margin-top: 4px;
      display: block;
    }
  }

  .phases-container {
    margin-bottom: 20px;

    h3 {
      margin-bottom: 12px;
    }
  }

  .phase-item {
    background-color: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;

    .phase-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      h4 {
        margin: 0;
      }
    }

    .phase-dates {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
  }

  .add-phase-btn {
    width: 100%;
    padding: 8px;
    margin-top: 8px;
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
  }
}
</style>